<?php
class InventoryController
{
    public $player;

    public $loaded = false;
    public $inventory = false;
    //$items[lib_id] = array(type,count);

    function  __construct($player) {
        $this->player = $player;
    }

    // adding inventory by id
    public function addInventory($id,$cnt = 1)
    {
        $this->load();
        if(!$id)
        {
            return false;
        }
        if(isset($this->inventory[$id]))
        {
            $this->inventory[$id][0] = $this->inventory[$id]+$cnt;
        }
        else
        {
            $this->inventory[$id] = $cnt;
        }
    }

    // out for client
    public function getAll()
    {
        $this->load();
        return $this->inventory;
    }

    // loading from database
    public function load()
    {
        if($this->loaded) return true;
        $query = 'SELECT `inventory` FROM `players_inventory` WHERE `user_id`='.$this->player->user_id;
        
        $data = _database::torow($query);
        if($data && is_array($data) && $data['inventory'])
        {
            $this->inventory = $this->unparse($data['inventory']);
        }
        else
        {
            $this->inventory = array();
        }
    }

    // unparse db string to array
    public function unparse($string)
    {
        $inventory = array();
        if($string)
        {
            $item_parts = explode('|',$string);
            if(is_array($item_parts))
            {
                foreach($item_parts as $part)
                {
                    list($id,$type,$count) = explode(';',$part);
                    if((int)$id && (int)$count && (int)$type)
                    $inventory[$this->getType((int)$type)][(int)$id] = array((int)$type,(int)$count);
                }
            }
        }
        return $inventory;
    }


    // parse array to db string
    public function parse()
    {
        
    }

    public function getType($type)
    {
        if($type == 1) return 'plant';
        return 'unknown';
    }
}
?>
